package com.zte.claa.inficombo.csa.app.service.rptparse;

import org.json.JSONObject;

import com.zte.claa.inficombo.csa.app.comm.csif.CSIFCommService;
import com.zte.claa.inficombo.csa.app.model.dev.DevJoinState;
import com.zte.claa.inficombo.csa.app.service.redis.PublishDataBuilder;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;
import com.zte.claa.inficombo.csa.app.util.XEuiUtils;

public class ParserDevJoinData extends ParserDefault {
	private static final String MSG_TYPE = "dev_join";
	
	public String getType() {
		return MSG_TYPE;
	}
	
	/**
	 * devjoin消息处理
	 * 
	 * {
		  "cmd": "dev_join",
		  "deveui": "2C26C50001FF0001",
		  "ver": "1.0",
		  "class": "B"
		}
	 */
	public void parseData(String jsonData, CSIFCommService svr) throws Exception {
		if(jsonData == null || jsonData.trim().equals("")){
			return;
		}
		JSONObject json = new JSONObject(jsonData);
		String devEui = JsonUtils.getJsonAttrVal(json, "deveui", null);
		if(devEui == null){
			logger.warn("ParserDevJoinData: deveui is null: "+jsonData);
			return;
		}
		// 1.解析消息.
		devEui = XEuiUtils.appendStartZero4xEUI(devEui);
		String devVer = JsonUtils.getJsonAttrVal(json, "ver", "1");
		String devClass = JsonUtils.getJsonAttrVal(json, "class", "A");
		DevJoinState devJS = new DevJoinState();
		devJS.setDevClass(devClass);
		devJS.setDevEUI(devEui);
		devJS.setDevVer(devVer);

		// 2.持久化保存；
		this.container.getPersisService().updateDevJoinState(devJS);
		logger.debug("Update dev join state ok: "+jsonData);
		
		// 3.redis发布通知
		String jsonMsg = PublishDataBuilder.buildDevJoinStateMsg(devJS);
		this.container.getStatePublisher().publishMessage(jsonMsg);
		logger.info("Publish dev join msg ok: "+jsonMsg);
	}
}
